package com.xian.wsim.service;

import com.xian.wsim.entity.MessageInfo;
import com.xian.wsim.repository.MessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
public class MessageService {

    @Autowired
    private MessageRepository messageRepository;

    /**
     * 获取指定用户之间指定时间范围内的历史消息
     * @param senderId 发送者ID
     * @param receiverId 接收者ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 消息列表
     */
    public List<MessageInfo> getMessagesBetween(Long senderId, Long receiverId, LocalDateTime startTime, LocalDateTime endTime) {
        if (startTime == null || endTime == null) {
            endTime = LocalDateTime.now();
            startTime = endTime.minusDays(2);
        }
        return messageRepository.findBySenderIdAndReceiverIdAndSendTimeBetweenOrSenderIdAndReceiverIdAndSendTimeBetween(
                senderId, receiverId, startTime, endTime,
                receiverId, senderId, startTime, endTime);
    }

    /**
     * 异步保存消息到数据库
     * @param messageInfo 消息信息
     * @return CompletableFuture对象
     */
    public CompletableFuture<Void> saveMessageToDBAsync(MessageInfo messageInfo) {
        return CompletableFuture.runAsync(() -> {
            messageRepository.save(messageInfo);
        });
    }
}